package com.dengdai.applibrary.https;


import android.os.Build;

import com.dengdai.applibrary.json.Jackson;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Vector;


/**
 * @说明 Http方法实现
 * @作者 LY
 * @时间 2015年6月11日 下午9:37:16
 * @版权 Copyright(c) 2014 LY-版权所有
 */
public class HttpRequesterNew {
    private String defaultContentEncoding;

    public HttpRequesterNew() {
        this.defaultContentEncoding = Charset.defaultCharset().name();
    }

    /**
     * 发送请求
     *
     * @param urlString  请求地址
     * @param method     请求方法名
     * @param parameters 参数
     * @param propertys  请求头信息
     * @return 结果集
     * @throws Exception
     */
    public HttpRespons send(String urlString, String method, Map<String, String> parameters, Map<String, String> propertys) throws Exception {
        HttpURLConnection urlConnection = null;
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod(method);
        urlConnection.setDoInput(true);
        if (Integer.parseInt(Build.VERSION.SDK) < 14) {
            urlConnection.setDoOutput(true);
        }
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(15000);

        if (method.equals(HttpMethods.PUT_METHODS)
                || method.equals(HttpMethods.POST_METHODS)
                || method.equals(HttpMethods.PATCH_METHODS)) {
            if (propertys != null) {
                propertys.put("Content-Type", "application/json");
                propertys.put("Accept", "application/json");
                for (String key : propertys.keySet()) {
                    urlConnection.addRequestProperty(key, propertys.get(key));
                }
            }
            JSONObject jsonObject = Jackson.getJSONObject(parameters);
            urlConnection.getOutputStream().write(jsonObject.toString().getBytes());
            urlConnection.getOutputStream().flush();
            urlConnection.getOutputStream().close();
        } else {
            if (propertys != null) {
                for (String key : propertys.keySet()) {
                    urlConnection.addRequestProperty(key, URLEncoder.encode(propertys.get(key), "utf-8"));
                }
            }
        }
        return this.makeContent(urlString, urlConnection);
    }


    /**
     * 得到响应对象
     *
     * @param urlConnection
     * @return 响应对象
     * @throws IOException
     */
    public HttpRespons makeContent(String urlString, HttpURLConnection urlConnection) throws IOException {
        HttpRespons httpResponser = new HttpRespons();
        try {
            InputStream in = urlConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
            httpResponser.contentCollection = new Vector<String>();
            StringBuffer temp = new StringBuffer();
            String line = bufferedReader.readLine();
            while (line != null) {
                httpResponser.contentCollection.add(line);
                temp.append(line).append("\r\n");
                line = bufferedReader.readLine();
            }
            bufferedReader.close();
            String ecod = urlConnection.getContentEncoding();
            if (ecod == null)
                ecod = this.defaultContentEncoding;
            httpResponser.urlString = urlString;
            httpResponser.cookie = urlConnection.getHeaderField("Set-Cookie");
            httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();
            httpResponser.file = urlConnection.getURL().getFile();
            httpResponser.host = urlConnection.getURL().getHost();
            httpResponser.path = urlConnection.getURL().getPath();
            httpResponser.port = urlConnection.getURL().getPort();
            httpResponser.protocol = urlConnection.getURL().getProtocol();
            httpResponser.query = urlConnection.getURL().getQuery();
            httpResponser.ref = urlConnection.getURL().getRef();
            httpResponser.userInfo = urlConnection.getURL().getUserInfo();
            httpResponser.content = new String(temp.toString().getBytes(), ecod);
            httpResponser.contentEncoding = ecod;
            httpResponser.code = urlConnection.getResponseCode();
            httpResponser.message = urlConnection.getResponseMessage();
            httpResponser.contentType = urlConnection.getContentType();
            httpResponser.method = urlConnection.getRequestMethod();
            httpResponser.connectTimeout = urlConnection.getConnectTimeout();
            httpResponser.readTimeout = urlConnection.getReadTimeout();
            return httpResponser;
        } catch (IOException e) {
            throw e;
        } finally {
            if (urlConnection != null)
                urlConnection.disconnect();
        }
    }


    /**
     * 默认的响应字符集
     */
    public String getDefaultContentEncoding() {
        return this.defaultContentEncoding;
    }

    /**
     * 设置默认的响应字符集
     */
    public void setDefaultContentEncoding(String defaultContentEncoding) {
        this.defaultContentEncoding = defaultContentEncoding;
    }

}
